package com.asus.open;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.view.MotionEvent;
import android.view.View;

import android.view.animation.Animation;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by asus1 on 2017/8/5.
 */

public class OpenPackageActivity extends Activity implements View.OnClickListener {
    private ImageView iv_card1;
    private ImageView iv_card2;
    private ImageView iv_card3;
    private ImageView iv_card4;
    private ImageView iv_card5;

    private RelativeLayout rl_parent;

    private ImageView iv_package;

    private boolean isopening = false; //是否正在打开卡牌包

    private ArrayList<Card> cardlist = Card.getCards();//获取全部卡牌
    private int card1 = 1;
    private int card2 = 2;
    private int card3 = 3;
    private int card4 = 4;
    private int card5 = 5;

    private boolean card1checked = false;//判断该卡牌是否已经翻转
    private boolean card2checked = false;
    private boolean card3checked = false;
    private boolean card4checked = false;
    private boolean card5checked = false;

    private boolean allcard = false;//5张卡牌是否全部被翻转

    private Button btn_ok;
    private TextView tv_number;

    private int packagenumber = 1;  //卡牌包数量（默认值为1）


    private float screenWidth;//屏幕宽高
    private float screenHeight;

    private static final Random RNG = new Random();

    private float downX;//初始焦点坐标
    private float downY;
    private float moveX;//焦点移动坐标
    private float moveY;

    private float olderX;//卡牌包初始坐标
    private float olderY;

    final Handler handler = new Handler();

    private final ReentrantLock lock = new ReentrantLock();

    private boolean firstmove = true; //第一次移动时确定初始坐标


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.openpackage);
        initView();
        Intent mIntent = getIntent();

        packagenumber = mIntent.getIntExtra("NUMBER", 1);
        tv_number.setText("剩余" + packagenumber + "包");
        iv_card1.setVisibility(View.INVISIBLE);
        iv_card2.setVisibility(View.INVISIBLE);
        iv_card3.setVisibility(View.INVISIBLE);
        iv_card4.setVisibility(View.INVISIBLE);
        iv_card5.setVisibility(View.INVISIBLE);
        btn_ok.setVisibility(View.INVISIBLE);

        btn_ok.setOnClickListener(this);
        iv_card1.setOnClickListener(this);
        iv_card2.setOnClickListener(this);
        iv_card3.setOnClickListener(this);
        iv_card4.setOnClickListener(this);
        iv_card5.setOnClickListener(this);


        iv_package.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                //如果正在打开卡牌包，则不做任何反应
                if (isopening) {
                    return true;
                }

                //触发该事件时初始化卡牌包原始坐标
                if (firstmove) {
                    olderX = iv_package.getX();
                    olderY = iv_package.getY();

                    screenWidth = rl_parent.getWidth();
                    screenHeight = rl_parent.getHeight();
                    firstmove = false;
                }

                switch (motionEvent.getAction()) {
                    //移动时该方法一直在重复调用
                    case MotionEvent.ACTION_DOWN:
                        //点下时获取初始焦点坐标（坐标1）
                        downX = motionEvent.getRawX();
                        downY = motionEvent.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        //移动时获取移动后坐标（坐标2）
                        moveX = motionEvent.getRawX();
                        moveY = motionEvent.getRawY();
                        iv_package.setX(iv_package.getX() + (moveX - downX));
                        iv_package.setY(iv_package.getY() + (moveY - downY));
                        //将坐标2赋值给坐标1（用于下次计算）
                        downX = moveX;
                        downY = moveY;
                        break;
                    case MotionEvent.ACTION_UP:
                        //屏幕失去焦点时触发该事件
                        //将firstmove设为true，用于下次触发时初始化卡牌包原始坐标
                        firstmove = true;
                        //将卡牌包移动至初始位置
                        iv_package.setX(olderX);
                        iv_package.setY(olderY);
                        //如果失去焦点前焦点位置在这个范围（背景中的凹槽）外，则不作任何反应
                        if (motionEvent.getRawX() < (screenWidth / 3)
                                || motionEvent.getRawX() > ((screenWidth / 30) * 19)
                                || motionEvent.getRawY() < ((screenHeight / 32) * 9)
                                || motionEvent.getRawY() > ((screenHeight / 32) * 19)) {
                            return true;
                        }
                        //将卡牌展示出来
                        iv_card1.setVisibility(View.VISIBLE);
                        iv_card2.setVisibility(View.VISIBLE);
                        iv_card3.setVisibility(View.VISIBLE);
                        iv_card4.setVisibility(View.VISIBLE);
                        iv_card5.setVisibility(View.VISIBLE);
                        //获取一张序号在1至30间的卡牌
                        do {
                            card1 = RNG.nextInt(31);
                            card2 = RNG.nextInt(31);
                            card3 = RNG.nextInt(31);
                            card4 = RNG.nextInt(31);
                            card5 = RNG.nextInt(31);
                        } while (
                                card1 == 0 || card2 == 0 || card3 == 0 || card4 == 0 || card5 == 0
                                );
                        //触发正在开包状态
                        isopening = true;
                        break;
                }
                return true;
            }
        });
    }

    private void initView() {
        rl_parent = findViewById(R.id.rl_parent);
        iv_card1 = findViewById(R.id.iv_card1);
        iv_card2 = findViewById(R.id.iv_card2);
        iv_card3 = findViewById(R.id.iv_card3);
        iv_card4 = findViewById(R.id.iv_card4);
        iv_card5 = findViewById(R.id.iv_card5);
        btn_ok = findViewById(R.id.btn_ok);
        iv_package = findViewById(R.id.iv_package);
        tv_number = findViewById(R.id.tv_number);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_card1:
                //如果卡牌已经被翻开，则不做任何反应
                if (card1checked) {
                    return;
                }
                //将卡牌设置为已翻开状态
                card1checked = true;
                //如果全部卡牌被翻开，设置全部卡牌已翻开状态
                if (card1checked && card2checked && card3checked && card4checked && card5checked) {
                    allcard = true;
                }
                //如果全部卡牌被翻开，使确定按钮可见
                if (allcard) {
                    allcard = false;
                    btn_ok.setVisibility(View.VISIBLE);
                }
                //开辟线程，用于寻找需要的卡牌，并播放2段动画
                Message message1 = Message.obtain(handler, new Runnable() {
                    @Override
                    public void run() {
                        lock.lock();
                        try {
                            for (int i = 0; i < cardlist.size(); i++) {
                                if (cardlist.get(i).getId() == card1) {
                                    final int carddrawable = cardlist.get(i).getDrawable();
                                    Rotation3dAnimation rotation3dAnimation = new Rotation3dAnimation(0, 90, 100, 0, 0, true, 400);
                                    iv_card1.startAnimation(rotation3dAnimation);
                                    rotation3dAnimation.setAnimationListener(new Animation.AnimationListener() {
                                        @Override
                                        public void onAnimationStart(Animation animation) {

                                        }

                                        @Override
                                        public void onAnimationEnd(Animation animation) {
                                            iv_card1.setBackgroundResource(carddrawable);
                                            iv_card1.startAnimation(new Rotation3dAnimation(270, 360, 100, 0, 0, true, 400));
                                        }

                                        @Override
                                        public void onAnimationRepeat(Animation animation) {

                                        }
                                    });
                                    break;
                                }
                            }
                        } finally {
                            lock.unlock();
                        }

                    }
                });
                message1.what = 1;
                handler.sendMessage(message1);
                break;
            case R.id.iv_card2:
                if (card2checked) {
                    return;
                }
                card2checked = true;
                if (card1checked && card2checked && card3checked && card4checked && card5checked) {
                    allcard = true;
                }
                if (allcard) {
                    allcard = false;
                    btn_ok.setVisibility(View.VISIBLE);
                }
                Message message2 = Message.obtain(handler, new Runnable() {
                    @Override
                    public void run() {
                        lock.lock();
                        try {
                            for (int i = 0; i < cardlist.size(); i++) {
                                if (cardlist.get(i).getId() == card2) {
                                    final int carddrawable = cardlist.get(i).getDrawable();
                                    Rotation3dAnimation rotation3dAnimation = new Rotation3dAnimation(0, 90, 100, 0, 0, true, 400);
                                    iv_card2.startAnimation(rotation3dAnimation);
                                    rotation3dAnimation.setAnimationListener(new Animation.AnimationListener() {
                                        @Override
                                        public void onAnimationStart(Animation animation) {

                                        }

                                        @Override
                                        public void onAnimationEnd(Animation animation) {
                                            iv_card2.setBackgroundResource(carddrawable);
                                            iv_card2.startAnimation(new Rotation3dAnimation(270, 360, 100, 0, 0, true, 400));
                                        }

                                        @Override
                                        public void onAnimationRepeat(Animation animation) {

                                        }
                                    });
                                    break;
                                }
                            }
                        } finally {
                            lock.unlock();
                        }

                    }
                });
                message2.what = 1;
                handler.sendMessage(message2);
                break;
            case R.id.iv_card3:
                if (card3checked) {
                    return;
                }
                card3checked = true;
                if (card1checked && card2checked && card3checked && card4checked && card5checked) {
                    allcard = true;
                }
                if (allcard) {
                    allcard = false;
                    btn_ok.setVisibility(View.VISIBLE);
                }
                Message message3 = Message.obtain(handler, new Runnable() {
                    @Override
                    public void run() {
                        lock.lock();
                        try {
                            for (int i = 0; i < cardlist.size(); i++) {
                                if (cardlist.get(i).getId() == card3) {
                                    final int carddrawable = cardlist.get(i).getDrawable();
                                    Rotation3dAnimation rotation3dAnimation = new Rotation3dAnimation(0, 90, 100, 0, 0, true, 400);
                                    iv_card3.startAnimation(rotation3dAnimation);
                                    rotation3dAnimation.setAnimationListener(new Animation.AnimationListener() {
                                        @Override
                                        public void onAnimationStart(Animation animation) {

                                        }

                                        @Override
                                        public void onAnimationEnd(Animation animation) {
                                            iv_card3.setBackgroundResource(carddrawable);
                                            iv_card3.startAnimation(new Rotation3dAnimation(270, 360, 100, 0, 0, true, 400));
                                        }

                                        @Override
                                        public void onAnimationRepeat(Animation animation) {

                                        }
                                    });
                                    break;
                                }
                            }
                        } finally {
                            lock.unlock();
                        }

                    }
                });
                message3.what = 1;
                handler.sendMessage(message3);
                break;
            case R.id.iv_card4:
                if (card4checked) {
                    return;
                }
                card4checked = true;
                if (card1checked && card2checked && card3checked && card4checked && card5checked) {
                    allcard = true;
                }
                if (allcard) {
                    allcard = false;
                    btn_ok.setVisibility(View.VISIBLE);
                }
                Message message4 = Message.obtain(handler, new Runnable() {
                    @Override
                    public void run() {
                        lock.lock();
                        try {
                            for (int i = 0; i < cardlist.size(); i++) {
                                if (cardlist.get(i).getId() == card4) {
                                    final int carddrawable = cardlist.get(i).getDrawable();
                                    Rotation3dAnimation rotation3dAnimation = new Rotation3dAnimation(0, 90, 100, 0, 0, true, 400);
                                    iv_card4.startAnimation(rotation3dAnimation);
                                    rotation3dAnimation.setAnimationListener(new Animation.AnimationListener() {
                                        @Override
                                        public void onAnimationStart(Animation animation) {

                                        }

                                        @Override
                                        public void onAnimationEnd(Animation animation) {
                                            iv_card4.setBackgroundResource(carddrawable);
                                            iv_card4.startAnimation(new Rotation3dAnimation(270, 360, 100, 0, 0, true, 400));
                                        }

                                        @Override
                                        public void onAnimationRepeat(Animation animation) {

                                        }
                                    });
                                    break;
                                }
                            }
                        } finally {
                            lock.unlock();
                        }

                    }
                });
                message4.what = 1;
                handler.sendMessage(message4);
                break;
            case R.id.iv_card5:
                if (card5checked) {
                    return;
                }
                card5checked = true;
                if (card1checked && card2checked && card3checked && card4checked && card5checked) {
                    allcard = true;
                }
                if (allcard) {
                    allcard = false;
                    btn_ok.setVisibility(View.VISIBLE);
                }
                Message message5 = Message.obtain(handler, new Runnable() {
                    @Override
                    public void run() {
                        lock.lock();
                        try {
                            for (int i = 0; i < cardlist.size(); i++) {
                                if (cardlist.get(i).getId() == card5) {
                                    final int carddrawable = cardlist.get(i).getDrawable();
                                    Rotation3dAnimation rotation3dAnimation = new Rotation3dAnimation(0, 90, 100, 0, 0, true, 400);
                                    iv_card5.startAnimation(rotation3dAnimation);
                                    rotation3dAnimation.setAnimationListener(new Animation.AnimationListener() {
                                        @Override
                                        public void onAnimationStart(Animation animation) {

                                        }

                                        @Override
                                        public void onAnimationEnd(Animation animation) {
                                            iv_card5.setBackgroundResource(carddrawable);
                                            iv_card5.startAnimation(new Rotation3dAnimation(270, 360, 100, 0, 0, true, 400));
                                        }

                                        @Override
                                        public void onAnimationRepeat(Animation animation) {

                                        }
                                    });
                                    break;
                                }
                            }
                        } finally {
                            lock.unlock();
                        }

                    }
                });
                message5.what = 1;
                handler.sendMessage(message5);
                break;
            case R.id.btn_ok:
                //初始化卡牌翻开状态
                card1checked = false;
                card2checked = false;
                card3checked = false;
                card4checked = false;
                card5checked = false;

                allcard = false;
                //结束卡牌被翻开状态
                isopening = false;
                //将一下视图设为不可见
                btn_ok.setVisibility(View.INVISIBLE);
                iv_card1.setVisibility(View.INVISIBLE);
                iv_card2.setVisibility(View.INVISIBLE);
                iv_card3.setVisibility(View.INVISIBLE);
                iv_card4.setVisibility(View.INVISIBLE);
                iv_card5.setVisibility(View.INVISIBLE);
                //初始化卡牌图案为卡背
                iv_card1.setBackgroundResource(R.drawable.cardback);
                iv_card2.setBackgroundResource(R.drawable.cardback);
                iv_card3.setBackgroundResource(R.drawable.cardback);
                iv_card4.setBackgroundResource(R.drawable.cardback);
                iv_card5.setBackgroundResource(R.drawable.cardback);
                //卡牌数量减1
                packagenumber--;
                //刷新卡牌剩余数量
                tv_number.setText("剩余" + packagenumber + "包");
                //如果无剩余卡牌，将卡牌包视图移除，并弹出提示
                if (packagenumber == 0) {
                    iv_package.setVisibility(View.INVISIBLE);
                    Toast.makeText(getApplication(), "无剩余卡包", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
